package wicketcool.core;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import wicketcool.common.configuration.WicketCoolConfiguration;
import wicketcool.core.exceptions.ConfigurationFileNotFoundException;
import wicketcool.core.exceptions.PluginDoesNotExistsException;
import wicketcool.plugins.InfoPlugin;
import wicketcool.plugins.Plugin;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * User: rabbit
 * Date: Jul 13, 2009
 */
@Component("core")
public class DefaultCore implements Core {

    @Autowired
    private Map<String, Plugin> plugins;

    private WicketCoolConfiguration configuration;


    @PostConstruct
    public void post() {
        InfoPlugin infoPlugin = (InfoPlugin) plugins.get("info");
        infoPlugin.setPlugins(plugins);
        configuration = new WicketCoolConfiguration(new HashMap<String, String>());
    }

    public void executePlugin(String pluginName, List<String> arguments)
            throws PluginDoesNotExistsException, ConfigurationFileNotFoundException {

        loadConfiguration(pluginName);

        if (plugins.containsKey(pluginName)) {
            plugins.get(pluginName).run(arguments, configuration);
        } else {
            throw new PluginDoesNotExistsException(pluginName);
        }

    }

    private void loadConfiguration(String pluginName) throws ConfigurationFileNotFoundException {

        if (!pluginName.equals("info")) {
            if (!new File(WicketCoolConfiguration.CONFIGURATION_FILE_NAME).exists()) {
                throw new ConfigurationFileNotFoundException();
            }

            Properties properties = readConfigurationFromFile();
            configuration.setProjectName(properties.getProperty("project.name"));
            configuration.setPackageName(properties.getProperty("package.name"));
            configuration.createDefaultsIfNeeded();
        }
    }    

    private Properties readConfigurationFromFile() {
        Properties properties = new Properties();
        try {
            properties.load(new FileReader(new File(WicketCoolConfiguration.CONFIGURATION_FILE_NAME)));
        } catch (IOException e) {
            throw new IllegalStateException("Could not load configuration", e);
        }

        return properties;
    }
}
